<template>
  <el-card class="certificate-list">
    <!-- 头部区域 -->
    <template #header>
      <page-header title="证书管理">
        <el-button type="primary" @click="handleBatchDownloadWrapper">
          <span class="desktop-text">打包下载二维码</span>
          <span class="mobile-text">批量下载</span>
        </el-button>
        <el-button type="primary" @click="handleAdd">添加证书</el-button>
      </page-header>
    </template>

    <!-- 搜索栏 -->
    <search-bar
      v-model="searchForm.certNumber"
      placeholder="输入证书编号搜索"
      :clearable="true"
      width="300px"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 视图切换控件 -->
    <div class="view-toggle">
      <el-radio-group v-model="viewMode" size="small">
        <el-radio-button value="list">
          <el-icon><List /></el-icon>
          列表模式
        </el-radio-button>
        <el-radio-button value="card">
          <el-icon><Grid /></el-icon>
          卡片模式
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 列表模式 -->
    <div v-if="viewMode === 'list'" v-loading="loading" class="certificate-table">
      <el-table :data="certificateList" border stripe style="width: 100%">
        <el-table-column prop="sequence_number" label="序号" width="80" header-align="center" align="center" />
        <el-table-column label="证书编号" min-width="160" header-align="center" align="center">
          <template #default="scope">
            {{ getCertNumber(scope.row.fields) }}
          </template>
        </el-table-column>
        <el-table-column label="项目名称" min-width="180" header-align="center" align="center">
          <template #default="scope">
            {{ getProjectName(scope.row.fields) }}
          </template>
        </el-table-column>
        <el-table-column label="委托单位" min-width="180" header-align="center" align="center">
          <template #default="scope">
            {{ getClientName(scope.row.fields) }}
          </template>
        </el-table-column>
        <el-table-column label="样品名称" min-width="160" header-align="center" align="center">
          <template #default="scope">
            {{ getSampleName(scope.row.fields) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" header-align="center" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'warning'" size="small">
              {{ scope.row.status === 'active' ? '启用中' : '停用中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="QR码" width="100" align="center" header-align="center">
          <template #default="scope">
            <el-popover placement="right" :width="200" trigger="hover">
              <template #reference>
                <el-button link type="primary" size="small">
                  <el-icon><Picture /></el-icon>
                </el-button>
              </template>
              <div style="text-align: center;">
                <img 
                  v-if="scope.row.qr_code_url" 
                  :src="scope.row.qr_code_url" 
                  alt="二维码" 
                  style="width: 150px; height: 150px; object-fit: contain;"
                  @error="handleQRCodeErrorWrapper(scope.row)"
                />
                <div v-else style="width: 150px; height: 150px; display: flex; align-items: center; justify-content: center;">
                  <el-icon :size="32" color="#909399"><Picture /></el-icon>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150" header-align="center" align="center">
          <template #default="scope">
            <el-tooltip 
              v-if="scope.row.custom_text" 
              :content="scope.row.custom_text" 
              placement="top" 
              :hide-after="2000"
            >
              <span>{{ scope.row.custom_text.length > 10 ? scope.row.custom_text.slice(0, 10) + '...' : scope.row.custom_text }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" header-align="center" align="center">
          <template #default="scope">
            <el-dropdown trigger="hover" @command="handleCommand($event, scope.row)">
              <el-button type="primary" size="small" class="operations-dropdown-btn">
                操作
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="view">
                    <el-icon><View /></el-icon> 查看
                  </el-dropdown-item>
                  <el-dropdown-item command="edit">
                    <el-icon><Edit /></el-icon> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="copy">
                    <el-icon><DocumentCopy /></el-icon> 复制
                  </el-dropdown-item>
                  <el-dropdown-item command="toggle">
                    <el-icon><SwitchButton /></el-icon> {{ scope.row.status === 'active' ? '停用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided class="danger-item">
                    <el-icon><Delete /></el-icon> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 卡片模式 -->
    <div v-else v-loading="loading" class="certificate-grid">
      <div
        v-for="cert in certificateList"
        :key="cert.id"
        class="certificate-item"
      >
        <!-- 序号 -->
        <div class="cert-number">
          <span class="cert-label">序号：</span>
          <span class="cert-value">{{ formatCertNumber(cert.sequence_number) }}</span>
        </div>

        <!-- 字段区域 -->
        <div class="cert-fields">
          <div class="fields-header">
            <div class="fields-title">证书字段</div>
            <div class="fields-actions">
              <el-button type="primary" link @click="handleBatchDelete(cert)" v-if="cert.selectedFields?.length">
                删除选中 ({{ cert.selectedFields.length }})
              </el-button>
              <el-button type="primary" link @click="handleAddField(cert)">
                添加字段
              </el-button>
            </div>
          </div>
          <div class="fields-content">
            <draggable 
              v-model="cert.fields" 
              item-key="field_name"
              handle=".drag-handle"
              :animation="200"
              @end="handleDragEnd(cert)"
            >
              <template #item="{ element: field }">
                <div class="field-item">
                  <div class="field-row">
                    <el-checkbox 
                      v-if="field.field_name !== 'cert_number'"
                      v-model="field.selected" 
                      @change="handleFieldSelect(cert, field)"
                    />
                    <el-checkbox 
                      v-else
                      disabled
                      style="visibility: visible; pointer-events: none;"
                    />
                    <div class="field-label">{{ field.name }}</div>
                    <el-input
                      v-model="field.description"
                      :placeholder="field.field_name === 'cert_number' ? '请输入证书编号(必填)' : '请输入描述'"
                    />
                    <el-icon 
                      v-if="field.field_name === 'cert_number'" 
                      class="forbidden-icon"
                    >
                      <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                        <circle cx="12" cy="12" r="10" />
                        <line x1="4" y1="20" x2="20" y2="4" />
                      </svg>
                    </el-icon>
                    <el-icon 
                      v-else
                      class="drag-handle"
                    >
                      <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                        <path d="M8 9h8M8 15h8" stroke-linecap="round"/>
                      </svg>
                    </el-icon>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </div>

        <!-- 二维码区域 -->
        <div class="qr-code-area">
          <div class="qr-actions">
            <div class="qr-code" style="display: none;">
              <img
                v-if="cert.qr_code_url"
                :src="cert.qr_code_url"
                alt="二维码"
                @error="handleQRCodeErrorWrapper(cert)"
              />
              <div v-else class="qr-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </div>
            <el-input
              v-model="cert.custom_text"
              placeholder="管理员备注（仅后台可见）"
              @change="handleCustomTextChange(cert)"
              class="admin-remark-input"
            />
            <div class="action-buttons-group">
              <div class="action-row">
                <el-button type="primary" link @click="handleDownload(cert)">下载二维码</el-button>
                <el-button type="primary" link @click="handleCopyLink(cert)">复制外链地址</el-button>
              </div>
            </div>
<div class="action-row">
  <el-button type="primary" size="small" @click="handleSave(cert)">
    <el-icon><Check /></el-icon> 保存
  </el-button>
  <el-button type="success" size="small" @click="handleCopyCertificate(cert)">
    <el-icon><DocumentCopy /></el-icon> 复制证书
  </el-button>
</div>
<div class="action-row">
  <el-button :type="cert.status === 'active' ? 'warning' : 'success'" size="small" @click="handleToggleStatus(cert)">
    <el-icon><SwitchButton /></el-icon> {{ cert.status === 'active' ? '停用' : '启用' }}
  </el-button>
  <el-button type="danger" size="small" @click="handleDelete(cert)">
    <el-icon><Delete /></el-icon> 删除
  </el-button>
</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <base-pagination
      v-model:current-page="currentPage"
      :total="total"
      :page-size="10"
      @update:current-page="handleCurrentChange"
    />

    <!-- 添加字段对话框 -->
    <el-dialog
      v-model="fieldDialogVisible"
      title="添加字段"
      width="500px"
      class="field-dialog"
    >
      <el-form
        ref="fieldFormRef"
        :model="fieldForm"
        label-width="100px"
      >
        <el-form-item label="选择字段" prop="field_names">
          <el-select
            v-model="fieldForm.field_names"
            placeholder="请选择字段"
            filterable
            multiple
            :multiple-limit="12"
            class="field-input"
          >
            <el-option
              v-for="field in dialogAvailableFields"
              :key="field.field_name"
              :label="field.name"
              :value="field.field_name"
            />
          </el-select>
        </el-form-item>
        <div class="field-select-tip">
          <el-text type="info" style="font-size: 14px;">可以选择多个字段（最多12个）</el-text>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fieldDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFieldSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加证书对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加证书"
      width="800px"
    >
      <div class="dialog-actions" style="margin-bottom: 15px;">
        <el-button 
          v-if="copiedCertificate" 
          type="success" 
          size="small"
          @click="handlePasteAgain"
          :icon="DocumentCopy"
        >重新粘贴</el-button>
        <el-button 
          v-if="copiedCertificate" 
          type="warning" 
          size="small"
          @click="handleClearCopied"
        >清除粘贴内容</el-button>
      </div>
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="120px"
      >
        <div v-for="index in 12" :key="index">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item :label="`字段${index}`">
                <el-select
                  v-model="addForm.fields[index-1].field_name"
                  placeholder="请选择字段"
                  clearable
                  :disabled="index === 1"
                  @change="handleFieldChange(index-1)"
                >
                  <el-option
                    v-for="field in getAvailableFields(index)"
                    :key="field.field_name"
                    :label="field.name"
                    :value="field.field_name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item 
                label="描述" 
                :prop="`fields.${index-1}.description`"
                :rules="index === 1 ? addFormRules['fields.0.description'] : []"
              >
                <el-input
                  v-model="addForm.fields[index-1].description"
                  :placeholder="index === 1 ? '请输入证书编号(必填)' : '请输入描述'"
                  :class="{'error-input': showFieldError(index-1)}"
                  @change="handleFieldValidation(index-1)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 添加管理员备注字段 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="管理员备注">
              <el-input
                v-model="addForm.custom_text"
                type="textarea"
                placeholder="管理员备注（仅后台可见）"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑证书对话框 -->
    <certificate-dialog
      v-model:visible="dialogVisible"
      :type="dialogMode"
      :data="currentCertificate"
      @success="handleDialogSuccess"
    />
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, h, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Picture, Plus, Document, DocumentCopy, List, Grid, View, Delete, SwitchButton, ArrowDown, Check, Edit } from '@element-plus/icons-vue'
import { certificateApi } from '@/api/certificateApi'
import { fieldApi } from '@/api/fieldApi'
import PageHeader from '@/components/PageHeader.vue'
import draggable from 'vuedraggable'
import { useQRCode } from '@/composables/useQRCode'
import { useFields } from '@/composables/useFields'
import { useFormValidation } from '@/composables/useFormValidation'
import BasePagination from '@/components/BasePagination.vue'
import SearchBar from '@/components/SearchBar.vue'
import CertificateDialog from '@/components/CertificateDialog.vue'

// 格式化证书序号
const formatCertNumber = (num) => {
  return num || '未生成'
}

// 数据列表
const certificateList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const page = ref(1)
const limit = ref(10)
const jumpPage = ref(1)

// 搜索表单
const searchForm = reactive({
  certNumber: ''
})

// 使用组合式函数
const {
  availableFields,
  fetchAvailableFields,
  getFieldName,
  handleFieldSelect,
  handleBatchDelete,
  addFields,
  getAvailableFields,
  getDialogAvailableFields
} = useFields()

// 使用表单验证
const {
  checkCertNumberDuplicate,
  validateFields,
  validateField,
  getFieldRules
} = useFormValidation(getFieldName)

// 字段相关
const fieldDialogVisible = ref(false)
const fieldFormRef = ref(null)
const fieldForm = reactive({
  certificate_id: null,
  field_names: []  // 改为数组以支持多选
})

// 添加证书相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)

// 存储复制的证书数据
const copiedCertificate = ref(null)

// 视图模式（列表或卡片）
const viewMode = ref('list') // 默认为列表模式

// 对话框相关
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentCertificate = ref(null)

// 初始化12个空字段
const initEmptyFields = () => {
  return Array(12).fill(null).map((_, index) => ({
    field_name: index === 0 ? 'cert_number' : '', // 第一个字段固定为证书编号
    description: '',
    error: false
  }));
}

const addForm = reactive({
  fields: initEmptyFields(),
  custom_text: ''
});

// 获取证书列表
const fetchCertificates = async () => {
  try {
    loading.value = true;
    const response = await certificateApi.getCertificates({
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    });
    
    // 恢复原有的数据结构处理
    if (response.code === 200) {
      // 创建一个基于 `availableFields` 的字段顺序映射
      const fieldOrderMap = new Map(
        availableFields.value.map((field, index) => [field.field_name, index])
      );

      // 在渲染前，对每个证书的字段按主列表顺序排序
      const sortedItems = (response.data.items || []).map(cert => {
        const sortedFields = [...cert.fields].sort((a, b) => {
          const orderA = fieldOrderMap.get(a.field_name);
          const orderB = fieldOrderMap.get(b.field_name);
          
          if (orderA === undefined) return 1;
          if (orderB === undefined) return -1;
          
          return orderA - orderB;
        });
        return { ...cert, fields: sortedFields };
      });

      certificateList.value = sortedItems;
      total.value = response.data.total;
    } else {
      throw new Error(response.message || '获取证书列表失败');
    }
  } catch (error) {
    console.error('获取证书列表失败:', error);
    ElMessage.error('获取证书列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  if (!searchForm.certNumber.trim()) {
    ElMessage.warning('请输入证书编号')
    return
  }
  currentPage.value = 1
  fetchCertificates()
}

// 重置搜索
const handleReset = () => {
  searchForm.certNumber = ''
  currentPage.value = 1
  fetchCertificates()
}

// 添加证书
const handleAdd = () => {
  // 检查是否有复制的证书
  if (copiedCertificate.value) {
    // 深拷贝复制的证书字段
    const copiedFields = JSON.parse(JSON.stringify(copiedCertificate.value.fields))
    
    // 找到证书编号字段并尝试递增
    const certNumberField = copiedFields.find(f => f.field_name === 'cert_number')
    if (certNumberField && certNumberField.description) {
      // 提取数字部分
      const match = certNumberField.description.match(/(\d+)/)
      if (match) {
        const numStr = match[0]
        const num = parseInt(numStr, 10)
        
        if (!isNaN(num)) {
          // 递增数字
          const nextNum = num + 1
          // 保持相同的前导零
          const paddedNum = nextNum.toString().padStart(numStr.length, '0')
          // 替换数字部分
          certNumberField.description = certNumberField.description.replace(numStr, paddedNum)
        }
      }
    }
    
    // 初始化12个字段以备新证书创建
    addForm.fields = initEmptyFields()
    
    // 将复制的字段填入表单中，但保留字段的数量
    copiedFields.forEach(field => {
      const index = addForm.fields.findIndex(f => !f.field_name || f.field_name === field.field_name)
      if (index !== -1) {
        addForm.fields[index] = { ...field }
      }
    })
    
    // 将复制的自定义文本添加到表单中
    addForm.custom_text = copiedCertificate.value.custom_text
    
    ElMessage.success('已粘贴证书数据，请检查证书编号是否重复')
  } else {
    // 如果没有复制的证书，则初始化空表单
    addForm.fields = initEmptyFields()
  }
  
  // 弹出添加对话框
  addDialogVisible.value = true
}

// 编辑证书
const handleEdit = (cert) => {
  dialogMode.value = 'edit'
  
  // 转换数据结构以适应表单
  const content = cert.fields.reduce((acc, field) => {
    acc[field.field_name] = field.description
    return acc
  }, {})
  
  currentCertificate.value = { 
    id: cert.id,
    content: content 
  }
  
  dialogVisible.value = true
}

// 处理对话框成功事件
const handleDialogSuccess = async () => {
  dialogVisible.value = false
  await fetchCertificates()
}

// 字段变更（用于已有证书的字段变更）
const handleExistingFieldChange = async (_cert, field) => {
  // 证书编号的变更已经在blur事件中处理
  if (field.field_name !== 'cert_number') {
    // 处理其他字段的变更...
  }
}

// 提交字段
const handleFieldSubmit = async () => {
  if (!fieldForm.field_names.length) {
    ElMessage.warning('请选择至少一个字段')
    return
  }

  try {
    const cert = certificateList.value.find(c => c.id === fieldForm.certificate_id)
    if (!cert) return
    
    // 使用新的addFields函数
    const success = await addFields(cert, fieldForm.field_names)
    if (success) {
      fieldDialogVisible.value = false
      fieldForm.field_names = []
      fieldForm.certificate_id = null
    }
  } catch (error) {
    console.error('Add fields error:', error)
    ElMessage.error('添加字段失败')
  }
}

// 添加字段
const handleAddField = (cert) => {
  fieldForm.certificate_id = cert.id
  fieldForm.field_names = []
  fieldDialogVisible.value = true
}

// 字段选择变更处理（用于新增证书时的字段选择）
const handleFieldChange = (index) => {
  // 如果清除了字段选择,同时清除描述
  if (!addForm.fields[index].field_name) {
    addForm.fields[index].description = ''
  }
  handleFieldValidation(index)
}

// 自定义文本变化
const handleCustomTextChange = (_cert) => {
  // 这里不实时保存，等用户点击保存按钮时统一保存
}

// 检查证书编号字段
const checkCertNumber = (fields) => {
  const certNumberField = fields.find(f => f.field_name === 'cert_number')
  if (!certNumberField) {
    return '尚未添证书编号字段'
  }
  if (!certNumberField.description) {
    return '缺少证书编号数据'
  }
  return null
}

// 表单校验规则
const addFormRules = {
  'fields.0.description': getFieldRules(0)
}

// 获取可选字段列表(第一行固定为证书编号，其他地方不能选择证书编号)
const dialogAvailableFields = computed(() => {
  if (!fieldForm.certificate_id) return []
  
  const cert = certificateList.value.find(c => c.id === fieldForm.certificate_id)
  if (!cert) return []
  
  return getDialogAvailableFields(cert)
})

// 获取描述字段校验规则
const getDescriptionRules = (index) => {
  if (index === 0) {
    return [{ required: true, message: '请输入证书编号', trigger: 'blur' }]
  }
  return []
}

// 显示字段错误状态
const showFieldError = (_index) => {
  return addForm.fields[_index].error
}

// 修改提交方法
const handleAddSubmit = async () => {
  try {
    // 检查必填项
    if (!addForm.fields[0].description) {
      ElMessage.warning('请输入证书编号')
      return
    }

    // 检查证书编号是否重复
    const isDuplicate = await checkCertNumberDuplicate(addForm.fields[0].description)
    if (isDuplicate) {
      addForm.fields[0].description = '' // 清空重复的证书编号
      return
    }

    // 过滤有效字段
    const validFields = addForm.fields.filter(field => 
      field.field_name || field.description?.trim()
    )
    
    // 验证字段完整性
    if (!validateFields(validFields.map(field => ({
      field_name: field.field_name,
      description: field.description
    })))) {
      return
    }

    if (validFields.length === 0) {
      ElMessage.warning('请至少填写一个字段')
      return
    }

    // 转换字段格式
    const fields = validFields.map(field => ({
      field_name: field.field_name,
      description: field.description.trim()
    }))

    const response = await certificateApi.createCertificate({
      fields,
      custom_text: addForm.custom_text || ''
    })

    if (response.code === 200) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      fetchCertificates()
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败，请重试')
  }
}

// 保存证书
const handleSave = async (cert) => {
  try {
    // 获取证书编号字段
    const certNumberField = cert.fields.find(f => f.field_name === 'cert_number')
    if (!certNumberField) {
      ElMessage.warning('缺少证书编号字段')
      return
    }

    // 检查证书编号是否重复
    const isDuplicate = await checkCertNumberDuplicate(certNumberField.description, cert.id)
    if (isDuplicate) {
      // 恢复原来的证书编号
      const originalCert = certificateList.value.find(c => c.id === cert.id)
      if (originalCert) {
        const originalCertNumber = originalCert.fields.find(f => f.field_name === 'cert_number')
        if (originalCertNumber) {
          certNumberField.description = originalCertNumber.description
          // 强制更新视图
          cert.fields = [...cert.fields]
        }
      }
      return
    }

    // 验证字段完整性
    if (!validateFields(cert.fields)) {
      return
    }

    // 只提取需要更新的字段
    const updateData = {
      fields: cert.fields,
      custom_text: cert.custom_text
    };

    const response = await certificateApi.updateCertificate(cert.id, updateData)
    
    if (response.code === 200) {
      // 如果保存成功，重新生成二维码
      cert.qr_code_url = ''
      const qrResponse = await certificateApi.regenerateQRCode(cert.id)
      if (qrResponse.code === 200) {
        cert.qr_code_url = qrResponse.data.qr_code_url
      }
      ElMessage.success('保存成功')
      fetchCertificates()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

// 复制外链地址
const handleCopyLink = (cert) => {
  const certNumber = getCertNumber(cert.fields)
  const url = `${window.location.origin}/view/${certNumber}`
  navigator.clipboard.writeText(url)
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch(() => {
      // 如果浏览器不支持 clipboard API使用传方法
      const input = document.createElement('input')
      input.value = url
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      ElMessage.success('复制成功')
    })
}

// 使用组合式函数
const { handleDownload, handleQRCodeError, handleBatchDownload, getCertNumber, getProjectName, getClientName, getSampleName } = useQRCode()

// 修改handleQRCodeError的调用
const handleQRCodeErrorWrapper = async (cert) => {
  try {
    if (!cert || !cert.id) {
      console.error('证书ID不存在:', cert)
      return
    }
    
    console.log('正在重新生成二维码，证书ID:', cert.id)
    
    // 先清空当前的二维码URL，显示占位图
    const originalUrl = cert.qr_code_url
    cert.qr_code_url = ''
    
    // 使用证书API判断证书是否存在
    try {
      // 尝试重新生成二维码
      await handleQRCodeError(cert, certificateApi.regenerateQRCode)
    } catch (regenerateError) {
      console.error('重新生成二维码失败:', regenerateError)
      // 如果404错误，说明证书不存在，显示占位符图片
      if (regenerateError.response && regenerateError.response.status === 404) {
        cert.qr_code_url = ''
      }
    }
  } catch (error) {
    console.error('二维码处理失败:', error)
    // 不显示错误消息，只在控制台记录，因为这可能是在页面加载时自动触发的
  }
}

// 删除重复的handleBatchDownload函数定义
// 删除从这里开始到window.URL.revokeObjectURL(url)的整个函数定义

// 删除证书
const handleDelete = (cert) => {
  ElMessageBox.confirm(
    '确定删除该证书吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await certificateApi.deleteCertificate(cert.id);
      ElMessage.success('删除成功');

      // 从本地列表移除，而不是重新获取
      const index = certificateList.value.findIndex(c => c.id === cert.id);
      if (index > -1) {
        certificateList.value.splice(index, 1);
        total.value--; // 更新总数
      }

      // 如果当前页为空，且不是第一页，则加载前一页
      if (certificateList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
        fetchCertificates();
      }

    } catch (error) {
      console.error('Delete certificate error:', error);
      ElMessage.error(error.message || '删除失败，请重试');
    }
  });
};

// 分页相关
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCertificates()
}

// 页码跳转
const handleJumpPage = () => {
  if (jumpPage.value > 0 && jumpPage.value <= Math.ceil(total.value / limit.value)) {
    page.value = jumpPage.value
    fetchCertificates()
  }
}

// 处理字段拖拽结束
const handleDragEnd = (cert) => {
  // 确保证书编号始终在第一位
  const certNumberField = cert.fields.find(f => f.field_name === 'cert_number')
  const otherFields = cert.fields.filter(f => f.field_name !== 'cert_number')
  cert.fields = [certNumberField, ...otherFields]
}

// 初始化
onMounted(async () => {
  console.log('CertificateList: onMounted 钩子触发');
  await fetchAvailableFields();
  await fetchCertificates();
})

// 切换回此页面时强制刷新数据
onActivated(async () => {
  console.log('CertificateList: onActivated 钩子触发');
  await fetchAvailableFields();
  await fetchCertificates();
})

// 切换状态
const handleToggleStatus = async (cert) => {
  try {
    // 当前是启用状态，要改为停用；当前是停用状态，要改为启用
    const willBeStatus = cert.status === 'active' ? 'inactive' : 'active'
    const actionText = willBeStatus === 'active' ? '启用' : '停用'
    
    await ElMessageBox.confirm(
      `确定要${actionText}该证书吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await certificateApi.toggleCertificateStatus(cert.id)
    if (res.code === 200) {
      // 立即更新本地状态
      cert.status = willBeStatus
      ElMessage.success(res.message || `${actionText}成功`)
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Toggle status error:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 添加批量下载的包装函数
const handleBatchDownloadWrapper = () => {
  // 过滤出有二维码的证书
  const certsWithQR = certificateList.value.filter(cert => cert.qr_code_path)
  if (certsWithQR.length === 0) {
    ElMessage.warning('没有可下载的二维码')
    return
  }
  handleBatchDownload(certsWithQR)
}

// 添加一个包装函数来处理字段验证
const handleFieldValidation = (index) => {
  const field = addForm.fields[index]
  validateField(field, index)
}

// 添加证书复制功能
const handleCopyCertificate = (cert) => {
  // 深拷贝证书数据
  copiedCertificate.value = {
    fields: JSON.parse(JSON.stringify(cert.fields)),
    custom_text: cert.custom_text || ''
  }
  
  ElMessage.success('证书已复制，可在添加证书时粘贴')
}

// 添加重新粘贴和清除粘贴的方法
const handlePasteAgain = () => {
  if (copiedCertificate.value) {
    // 重新复制一遍，可能会再次递增证书编号
    const copiedFields = JSON.parse(JSON.stringify(copiedCertificate.value.fields))
    
    // 找到证书编号字段并尝试递增
    const certNumberField = copiedFields.find(f => f.field_name === 'cert_number')
    if (certNumberField && certNumberField.description) {
      // 提取数字部分
      const match = certNumberField.description.match(/(\d+)/)
      if (match) {
        const numStr = match[0]
        const num = parseInt(numStr, 10)
        
        if (!isNaN(num)) {
          // 递增数字
          const nextNum = num + 1
          // 保持相同的前导零
          const paddedNum = nextNum.toString().padStart(numStr.length, '0')
          // 替换数字部分
          certNumberField.description = certNumberField.description.replace(numStr, paddedNum)
        }
      }
    }
    
    // 初始化12个字段以备新证书创建
    addForm.fields = initEmptyFields()
    
    // 将复制的字段填入表单中
    copiedFields.forEach(field => {
      const index = addForm.fields.findIndex(f => !f.field_name || f.field_name === field.field_name)
      if (index !== -1) {
        addForm.fields[index] = { ...field }
      }
    })
    
    // 将复制的自定义文本添加到表单中
    addForm.custom_text = copiedCertificate.value.custom_text
    
    ElMessage.success('已重新粘贴证书数据，证书编号已递增')
  }
}

const handleClearCopied = () => {
  copiedCertificate.value = null
  ElMessage.success('已清除粘贴的证书数据')
}

// 查看证书详情（列表模式）
const handleViewDetails = (cert) => {
  // 在当前位置展开证书详情
  cert.showDetails = !cert.showDetails
  if (!cert.showDetails) return

  // 构建表格式的详情内容
  const renderDetailContent = () => {
    const fields = cert.fields.map(field => {
      return h('tr', {}, [
        h('td', { class: 'detail-field-label' }, getFieldName(field.field_name)),
        h('td', { class: 'detail-field-value' }, field.description || '-')
      ])
    })

    // 创建表格
    const detailTable = h('table', { class: 'cert-detail-table' }, [
      ...fields
    ])

    return h('div', { class: 'cert-details-container' }, [
      detailTable
    ])
  }

  // 使用对话框显示
  ElMessageBox({
    title: `证书详情 (序号: ${formatCertNumber(cert.sequence_number)})`,
    message: renderDetailContent(),
    customClass: 'cert-details-dialog',
    showCancelButton: false,
    showClose: false,
    confirmButtonText: '关闭',
    beforeClose: (action, instance, done) => {
      done()
    }
  })
}

// 处理下拉菜单命令
const handleCommand = (command, row) => {
  switch (command) {
    case 'view':
      handleViewDetails(row)
      break
    case 'edit':
      handleEdit(row)
      break
    case 'copy':
      handleCopyCertificate(row)
      break
    case 'toggle':
      handleToggleStatus(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'save':
      handleSave(row)
      break
  }
}
</script>

<style>
/* 全局样式，不使用scoped */
.cert-details-dialog {
  min-width: 550px !important;
  border-radius: 8px;
  overflow: hidden;
}

.cert-details-dialog .el-message-box__content {
  padding: 0 !important;
}

.cert-details-dialog .el-message-box__header {
  padding: 15px 0;
  margin: 0 0 10px;
  background-color: #4a89dc;
  border-bottom: none;
  text-align: center;
  border-radius: 8px 8px 0 0;
}

.cert-details-dialog .el-message-box__title {
  font-weight: bold;
  color: white;
  font-size: 16px;
}

.cert-details-dialog .el-message-box__headerbtn .el-icon {
  color: rgba(255, 255, 255, 0.8);
}

.cert-details-dialog .el-message-box__headerbtn:hover .el-icon {
  color: white;
}

.cert-details-dialog .el-message-box__message {
  margin: 0 !important;
}

/* 底部按钮区域样式 */
.cert-details-dialog .el-message-box__btns {
  padding: 10px 20px 15px;
  text-align: center;
}

.cert-details-dialog .el-button--primary {
  background-color: #4a89dc;
  border-color: #4a89dc;
  padding: 8px 25px;
  font-size: 14px;
}

.cert-details-dialog .el-button--primary:hover,
.cert-details-dialog .el-button--primary:focus {
  background-color: #5d9bea;
  border-color: #5d9bea;
}

/* 证书详情表格样式 */
.cert-details-container {
  width: 100%;
}

.cert-detail-table {
  width: 100%;
  border-collapse: collapse;
  border: none;
  margin: 0;
}

.cert-detail-table tr {
  border: none;
}

.cert-detail-table td {
  padding: 12px 15px;
  border: 1px solid #fff;
}

.cert-detail-table td.detail-field-label {
  width: 120px;
  background-color: #d9eafa;
  color: #333;
  font-weight: normal;
  text-align: center;
}

.cert-detail-table td.detail-field-value {
  background-color: #fff;
  color: #333;
  text-align: left;
}
</style>

<style lang="scss" scoped>
.certificate-list {
  height: 100%;
  margin: -20px;
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__header) {
    padding: 0;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  :deep(.el-card__body) {
    padding: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .certificate-grid {
      flex: 1;
      overflow-y: auto;
      padding: 16px 20px;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }
  }
}

.certificate-grid {
  padding: 16px 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.certificate-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cert-number {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;

  .cert-label {
    color: #606266;
    font-size: 14px;
  }

  .cert-value {
    color: #303133;
    font-weight: 500;
  }
}

.cert-fields {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;

  .fields-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .fields-title {
      font-size: 14px;
      color: #606266;
    }

    .fields-actions {
      display: flex;
      gap: 8px;
    }
  }

  .fields-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .field-item {
    margin-bottom: 0px;

    .field-row {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 2px;
      background: #f8f9fa;
      border-radius: 4px;

      .field-label {
        width: 80px;
        color: #606266;
        font-size: 14px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .el-input {
        flex: 1;
      }

      .forbidden-icon {
        color: #909399;
        cursor: not-allowed;
      }

      .drag-handle {
        color: #909399;
        cursor: move;
      }
    }
  }
}

.qr-code-area {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;

  .qr-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;

    .qr-code {
      width: 120px;
      height: 120px;
      background: #fff;
      border-radius: 4px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .qr-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
        font-size: 24px;
      }
    }

    .admin-remark-input {
      width: 100%;
    }

    .action-buttons-group {
      width: 100%;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .action-row {
      display: flex;
      gap: 8px;
      justify-content: flex-start;
      width: 100%;

      .el-button {
        flex: 1;
      }
    }
  }
}

.field-dialog {
  .field-input {
    width: 100%;
  }

  .field-select-tip {
    margin-top: 8px;
    color: #909399;
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .desktop-text {
    display: none;
  }
  
  .fields-container {
    max-height: 240px;
  }
  
  .field-checkbox {
    width: calc(50% - 10px);
  }
}

@media screen and (min-width: 769px) {
  .mobile-text {
    display: none;
  }
}

// 视图切换控件样式
.view-toggle {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
  padding: 0 20px;
}

// 列表模式样式
.certificate-table {
  padding: 0 20px 20px;

  :deep(.el-table) {
    margin-bottom: 16px;
    
    .el-table__header-wrapper th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: bold;
      text-align: center;
    }
    
    .table-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      
      .el-button {
        margin: 3px 0;
      }
    }

    /* 自定义斑马线颜色 */
    .el-table__row--striped td {
      background-color: #f8fafd;
    }
  }
}

// 证书详情对话框样式 - 移除与全局样式冲突的部分
:deep(.cert-details-dialog) {
  max-height: 70vh;
  overflow-y: auto;
}

.desktop-table {
  padding: 20px;
}

// 操作下拉菜单样式
.operations-dropdown-btn {
  width: 80px;
}

.card-operations-dropdown {
  width: 100%;
  
  :deep(.el-dropdown-selfdefine) {
    width: 100%;
    
    .el-button {
      width: 100%;
    }
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
  
  .el-icon {
    margin-right: 5px;
  }

  &.danger-item {
    color: var(--el-color-danger);
    
    .el-icon {
      color: var(--el-color-danger);
    }
  }
}
</style> 